import React, { useEffect, useState } from "react";
import { inject, observer } from "mobx-react";
import { uuid } from "./utils";
import "./styles.css";

function App(props) {
  const [text, setText] = useState("");
  useEffect(() => {
    props.fetchTodos();
  }, []);
  if (props.loading) {
    return <h1>loading...</h1>;
  }
  const handleToggleComplete = (id) => {
    props.toggleComplete(id);
  };
  const addItem = () => {
    props.addItem({
      text,
      id: uuid()
    });
    setText("");
  };
  const deleteItem = (id) => {
    props.deleteItem(id);
  };
  const onChange = (e) => {
    setText(e.target.value);
  };
  return (
    <>
      <div style={{ display: "flex" }}>
        <input
          type="text"
          placeholder="添加新的待办"
          value={text}
          onChange={onChange}
        />
        <button onClick={addItem}>添加</button>
      </div>
      <ul className="todoList">
        {props.todos.map((item) => {
          console.log("item", item);
          return (
            <div style={{ display: "flex", alignItems: "center", height: 50 }}>
              <li key={item.id}>{item.text}</li>
              <input
                type="checkbox"
                checked={Boolean(item.isComplete)}
                onChange={() => handleToggleComplete(item.id)}
              />
              <button
                style={{ marginLeft: 20 }}
                onClick={() => deleteItem(item.id)}
              >
                删除
              </button>
            </div>
          );
        })}
      </ul>
      <div data-id={props.completeCount}>{console.log(1111)}个</div>
    </>
  );
}

const mapStoreToProps = ({ store }) => {
  console.log("store", store);
  return {
    todos: store.todos,
    loading: store.loading,
    fetchTodos: store.fetchTodos,
    completeCount: store.completeCount,
    toggleComplete: store.toggleComplete,
    addItem: store.addItem,
    deleteItem: store.deleteItem,
    showLoading: store.showLoading,
    hideLoading: store.hideLoading
  };
};

export default inject(mapStoreToProps)(observer(App));
